<template>
	<view class="container">
		<!-- #ifndef MP -->
		<view class="logo">
			<view class="img">
				<image mode="widthFix" src="/static/img/public/myl.png"></image>
			</view>
			<view class="text">牧耘郎</view>
		</view>
		<!-- 账号密码输入框 -->
		<view class="form login">
			<view class="username">
				<image class="img" src="/static/img/public/account.png" mode="widthFix"></image>
				<input placeholder="请输入手机号" v-model="phoneNumber" maxlength="11" type="number" placeholder-style="color: rgba(172,173,174,0.8);" />
			</view>
			<view class="code" v-if="type == 0">
				<image class="code_img" src="/static/img/public/verificationCode.png" mode="widthFix"></image>
				<view class="get-code" :style="{'color':getCodeBtnColor}" @click.stop="getCode()">{{getCodeText}}</view>
				<input placeholder="请输入验证码" v-model="code" :focus="codeFocus" placeholder-style="color: rgba(172,173,174,0.8);" />
			</view>
			<view class="password" v-else>
				<image class="code_img" src="/static/img/public/password.png" mode="widthFix"></image>
				<input placeholder="请输入密码" v-model="passwd" :password="true" type="number" placeholder-style="color: rgba(172,173,174,0.8);" />
			</view>
			<view class="btn" @tap="doLogin">登 录</view>
			<view class="res">
				<text v-if="type == 0" @tap="changeLogin(1)">账号密码登录</text>
				<view v-else>
					<text @tap="changeLogin(0)">验证码登录</text>
					<text @tap="toPage('repassword')" style="margin-left: 10upx;">忘记密码</text>
				</view>
				<text @tap="toPage('register')">新用户注册</text>
			</view>
		</view>
		<!-- 第三方登录 -->
		<view class="oauth" v-if="isShowOauth">
			<view class="text">———————— &nbsp;其它登录方式 &nbsp;————————</view>
			<view class="list">
				<view @tap="oauthLogin('weixin')" v-if="showProvider.weixin" class="yticon icon-weixin"></view>
				<!-- <view class="yticon"><image src=/statict/qq.png></image></view> -->
				<!-- <view @tap="oauthLogin('qq')" v-if="showProvider.qq" class="yticon icon-qq"></view> -->
				<!-- <view @tap="oauthLogin('sinaweibo')" v-if="showProvider.sinaweibo" class="yticon sinaweibo"></view> -->
			</view>
		</view>
		<!-- #endif -->
		<!-- #ifdef MP -->
		<view class="logo" style="margin: 200upx 0 150upx 0;">
			<view class="img">
				<image mode="widthFix" src="/static/img/public/myl.png"></image>
			</view>
			<view class="text">牧耘郎</view>
		</view>
		<button class="miniAppLogin" style="margin-bottom: 100upx;" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">微信登录</button>
		<!-- #endif -->

		<view class="protocol_container">
			<view class="protocol_content">
				<text class="box_title">登录即代表同意</text>
				<view class="protocol">
					<text @tap="doProtocol('https://download.dfkjt.com/userRegistrationAgreement.txt', '用户协议')">《用户协议》</text>
					<text>和</text>
					<text @tap="doProtocol('https://download.dfkjt.com/re_privacyPolicy.txt', '用户隐私保护政策')">《用户隐私保护政策》</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex';
	import Api from '@/common/api';
	import md5 from "@/common/SDK/md5.min.js";
	import JSEncrypt from "@/common/SDK/jsencrypt";
	import uniIcons from "@/components/uni-icons/uni-icons.vue"

	export default {
		components: {
			uniIcons
		},
		data() {
			return {
				loginCore: '',
				phoneNumber: '',
				code: '',
				passwd: '',
				sid: '',
				timestamp: "",
				publicKey: "",
				privateKey: "",
				getCodeText: '验证码',
				codeFocus: false, //验证码输入框是否聚焦
				type: 0, // 默认0为账号+短信验证码登录，1为登录+密码登录
				getCodeBtnColor: "#767777",
				isShowOauth: false,
				logining: false,
				strUrl: null,
				showProvider: {
					weixin: false,
					qq: false,
					sinaweibo: false,
					xiaomi: false
				}
			}
		},
		onShow() {

		},
		onLoad(option) {
			this.strUrl = option.strUrl;

			//uni-app判断客户端环境是 android、ios 还是小程序开发工具
			let phone_system = uni.getSystemInfoSync().platform;
			if (phone_system != "ios") {
				//客户端环境是ios时不显示第三方授权登录
				// this.isShowOauth=true
				//APP显示第三方登录			
				// #ifdef APP-PLUS
				this.isShowOauth = true;
				this.getProvider();
				// #endif
			}
			// #ifdef MP
			uni.login({
				success: (e) => {
					console.log(e)
					this.loginCore = e.code;
				}
			})
			// #endif
		},
		onShow() {
			this.get_secret_key(); //获取服务器端秘钥
			this.get_public_privatekey(); //获取客户端密钥和私钥
		},
		methods: {
			...mapMutations(['login']),
			changeLogin(num) {
				this.type = Number(num);
				// uniapp动态改变导航标题navigationBarTitleText
				// uni.setNavigationBarTitle({
				// 	title: '账号密码登录'
				// });
			},
			// async
			async getCode() {
				// this.logining = true;
				uni.hideKeyboard()
				if (this.getCodeisWaiting) {
					return;
				}
				if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phoneNumber))) {
					uni.showToast({
						title: '请填写正确手机号码',
						icon: "none"
					});
					return false;
				}
				this.getCodeText = "发送中..."
				this.codeFocus = true;
				this.getCodeisWaiting = true;
				// this.getCodeBtnColor = "rgba(255,255,255,0.5)"
				var mobile = {
					'mobile': this.phoneNumber
				};
				let data = await Api.apiCall('post', Api.index.sendCodes, mobile);
				if (data) {
					//示例用定时器模拟请求效果
					setTimeout(() => {
						uni.showToast({
							title: '验证码已发送',
							icon: "success"
						});
						this.setTimer();
					}, 500)
				} else {
					this.getCodeisWaiting = false;
					this.getCodeText = "验证码";

					uni.showToast({
						title: data.error,
						icon: 'none'
					});

				}

			},
			setTimer() {
				let holdTime = 60;
				this.getCodeText = "60秒"
				this.Timer = setInterval(() => {
					if (holdTime <= 0) {
						this.getCodeisWaiting = false;
						this.getCodeBtnColor = "#767777";
						this.getCodeText = "验证码"
						clearInterval(this.Timer);
						return;
					}
					this.getCodeText = holdTime + "秒"
					holdTime--;
				}, 1000)
			},
			oauthLogin(provider) {
				var _this = this;
				// var getAppid = plus.runtime.appid;
				uni.showLoading({
					title: '加载中'
				});

				// // #ifdef MP
				// //第三方登录 微信小程序/支付宝小程序/百度小程序/头条小程序/QQ小程序
				// uni.login({
				// 	provider: provider,
				// 	success: (loginRes) => {
				// 		// plus.nativeUI.alert("**code**" + JSON.stringify());
				// 		// console.log("success: " + JSON.stringify(loginRes));
				// 		let code = loginRes.code,
				// 			type = 'weixin';
				// 		uni.setStorageSync('wx_code', code);
				// 		_this.getUserInfo(code, type);
				// 		//案例直接获取用户信息，一般不是在APP端直接获取用户信息，比如微信，获取一个code，传递给后端，后端再去请求微信服务器获取用户信息				
				// 		uni.hideLoading();
				// 	},
				// 	fail: (e) => {
				// 		plus.nativeUI.alert("fail: " + JSON.stringify(e));
				// 		console.log("fail: " + JSON.stringify(e));
				// 	}
				// });
				// // #endif

				// #ifdef APP-PLUS
				// APP中第三方微信授权登录;
				let Service, all;
				plus.oauth.getServices((services) => {
					// console.log('***services****', JSON.stringify(services));
					if (services && services.length) {
						all = services;
						Object.keys(all).some((key) => {
							if (all[key].id == provider) Service = all[key]
							// console.log('***授权对象***', JSON.stringify(Service))
						})

						//没有微信登录授权服务
						if (!Service) return;
						// console.log('***开始授权了***');

						Service.authorize((e) => { //此处获取code的关键
							console.log('这次是真的授权后返回的code', e.code)
							let code = e.code,
								type = 'weixin';
							uni.setStorageSync('wx_code', code);
							this.getUserInfo(code, type);
							uni.hideLoading();

						}, (error) => {
							uni.hideLoading();
						}, {
							// console.log('****getAppid****',getAppid);
							// http://www.html5plus.org/doc/zh_cn/oauth.html#plus.oauth.AuthOptions
							// appid: getAppid, //开放平台的应用标识。暂时填个假的充数，仅做演示。
						});
					} else {
						uni.hideLoading();
						plus.nativeUI.alert("无可用的登录授权服务");
						console.log('无可用的登录授权服务');
					}
				}, (error) => {
					console.error('getServices fail:' + JSON.stringify(error));
				});
				// #endif

			},
			getProvider() {
				//获取第三方登录服务
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						console.log('*******获取第三方登录服务res********', JSON.stringify(res));
						//有服务才显示按钮图标
						res.provider.forEach(e => {
							this.showProvider[e] = true
						})
						if (res.provider.length == 0) this.isShowOauth = false;
					}
				});
			},
			doProtocol(url, title) {
				if (!url) {
					uni.showToast({
						title: '还未上传相关协议',
						icon: "none"
					});
					return;
				}
				uni.navigateTo({
					url: `/pages/public/protocol?url=${url}&title=${title}`
				})

			},

			toPage(page) {
				uni.hideKeyboard();
				if (!page) {
					uni.showToast({
						title: '暂未开通',
						icon: "success"
					});
					return false;
				}
				uni.navigateTo({
					url: page
				});
			},
			doLogin() {
				uni.hideKeyboard();
				this.logining = true;
				let phoneReg = /^1[1-9][0-9]\d{8}$/;
				//验证手机号码
				if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phoneNumber))) {
					uni.showToast({
						title: '请填写正确手机号码',
						icon: "none"
					});
					return false;
				}
				try {
					if (this.phoneNumber == '') {
						throw '请填写手机号';
					}
					if (!phoneReg.test(this.phoneNumber)) {
						throw '手机号格式有误';
					}
					if (this.type == 0 && this.code.length != 6) {
						throw '请输入6位验证码';
					}
					if (this.type == 1 && this.passwd.length == 0) {
						throw '密码不能为空'
					}
				} catch (err) {
					uni.showToast({
						title: err,
						icon: "none"
					});
					return;
				}
				// 默认0为账号+短信验证码登录，1为登录+密码登录
				if (this.type == 1) {
					this.getUserInfo(this.passwd, 'default');
				} else {
					this.getUserInfo(this.code, 'captcha');
				}

			},
			async getUserInfo(code, type) {
				// debugger
				// 从服务器获取用户数据

				let secret_key = uni.getStorageSync('secret_key'); //获取服务器公钥
				this.privateKey = uni.getStorageSync('privateKey');
				this.publicKey = uni.getStorageSync('publicKey');
				let info = JSON.stringify({
					"type": type,
					"mobile": this.phoneNumber,
					"secret": code
				});
				let encryptor = new JSEncrypt({
					default_key_size: 1024
				});
				// encryptor.getKey();
				encryptor.setPublicKey(secret_key); //创建加密对象
				// var encrypt_txt = rsa.encrypt(info, key, pkcs=8)
				let encrypt_txt = encryptor.encrypt(info); //生成加密字符串
				let params = {
					"secret_key": secret_key,
					"content": encrypt_txt,
					"client_key": this.publicKey
				}
				let data = await Api.apiCall('post', Api.index.login, params);
				if (data.code == 0) {
					let decryptor = new JSEncrypt({
						default_key_size: 1024
					});
					decryptor.setPrivateKey(this.privateKey);
					let decrypt_txt = decryptor.decrypt(data.data.content); //解密
					decrypt_txt = JSON.parse(decrypt_txt); //json字符串转Json对像
					if (decrypt_txt.token) {
						let userInfo = {
							sid: data.sid,
							mobile: this.phoneNumber,
							token: decrypt_txt.token
						}
						this.login(userInfo); //保存登录缓存
						this.joinCart(); //用户登录成功把客户端购物车缓存的数据添加服务器
						if (this.strUrl == 'setpasswd') {
							uni.switchTab({
								url: '/pages/user/user',
							});
						} else {
							uni.navigateBack();
						}

					} else {
						this.logining = false;
					}
				} else if (data.code == 10006) {
					// 无效秘钥时：清空秘钥==》 重新获取服务器秘钥 ==》 模拟用户登录
					uni.removeStorage({
						key: 'secret_key'
					})
					this.get_secret_key(); //获取服务器端秘钥
					let secret_new_key = uni.getStorageSync('secret_key')
					if (secret_new_key) {
						this.getUserInfo(code, type); //模拟用户再次登录
					}
				} else if (data.code == 10007) {
					uni.showToast({
						title: '账号不存在，请先注册',
						icon: 'none'
					});
					setTimeout(function() {
						uni.navigateTo({
							url: 'register',
						});
					}, 2000)
				} else if (data.code == 100008) {
					plus.nativeUI.alert("未绑定手机号码");
					uni.navigateTo({
						url: 'bind_mobile'
					})
				} else if (data.code == 10011) {
					//帐号未注册，登录还差一步就完成!
					uni.showToast({
						title: '未注册账号，将自动为你注册',
						icon: 'none'
					});
					setTimeout(function() {
						uni.navigateTo({
							url: '/pages/public/setpasswd?mobile=' + this.phoneNumber,
						});
					}, 2000)
				} else {
					uni.showToast({
						title: data.error,
						icon: 'none'
					});
				}
			},
			//获取秘钥
			async get_secret_key() {
				var params = {};
				// 获取服务器端公钥私钥
				var secret_key = uni.getStorageSync('secret_key');
				if (!secret_key) {
					let data = await Api.apiCall('post', Api.index.get_lock, params);
					if (data) {
						uni.setStorageSync('secret_key', data.secret_key);
					}
				}
			},
			// 重新获取客户端公钥和私钥
			get_public_privatekey() {
				let privateKey = uni.getStorageSync('privateKey');
				let publicKey = uni.getStorageSync('publicKey');
				if (!publicKey || !privateKey) {
					//客户端生成秘钥对
					// 返回数组 array[0]公钥  array[1]私钥
					var crypt = new JSEncrypt({
						default_key_size: 1024
					});
					crypt.getKey();
					var crypt_publicKey = crypt.getPublicKey();
					var crypt_privateKey = crypt.getPrivateKey();
					// 去除-----*** RSA **** KEY----- 和空格换行
					crypt_publicKey = (crypt_publicKey.split('-----'))[2];
					// publicKey = publicKey.replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "").replace(/\s*/g, "");
					crypt_privateKey = (crypt_privateKey.split('-----'))[2];
					uni.setStorageSync('publicKey', crypt_publicKey);
					uni.setStorageSync('privateKey', crypt_privateKey);
				}
			},
			async joinCart() {
				//用户未登录状态时，把购物车缓存数据同步到服务器端购物车中;
				let params = {
						'sku_list': await uni.getStorageSync('cartList')
					},
					data = await Api.apiCall('put', Api.order.Cart, params);
				if (data) {
					uni.removeStorage({
						key: 'cartList'
					});
					uni.navigateBack();
				}
			},
			async wxMiniCodeAuth(encryptedData, iv)
			{
				var _this = this;
				var params = {
					"secret": _this.loginCore,
					"app_type": "mini",
					"encryptedData": encryptedData,
					"iv": iv
				}
				let res = await Api.apiCall('post', Api.index.wxMiniCodeAuth, params);
				console.log("***phoneNumber****",JSON.stringify(res))
				if (res) {
					_this.logining = true;
					let type = 'mini';
					_this.phoneNumber = res.phoneNumber;
					
					// 微信授权成功后，模拟用户登录
					_this.getUserInfo(_this.loginCore, type);
				}
			},
			getPhoneNumber(e) {
				var _this = this;
				if (e.detail.errMsg.includes('ok')) {
					console.log(e)
					console.log('***this.loginCore****',_this.loginCore)
					let {
						encryptedData,
						iv
					} = e.detail;
					_this.wxMiniCodeAuth(encryptedData, iv);
					
				}
			},
			
		}
	}
</script>

<style lang="scss">
	@import "../../static/css/login.scss";



	.miniAppLogin {
		background-color: #FFBC21;
		color: #FFF;
		width: 100%;
		height: 80upx;
		border-radius: 5upx;
		font-size: 28upx;
	}


	.form {
		width: 100%;

		.res {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 100upx;
			font-size: 28upx;
			color: rgba($color: #767777, $alpha: 0.8);
		}
	}

	.protocol_container {
		// position: absolute;
		// width: 100%;
		// bottom: 20upx;
		width: 100%;
		margin-top: 10upx;

		.protocol_content {
			width: 100%;
			// height: 50upx;
			display: flex;
			flex-flow: column wrap;
			align-items: center;
			font-size: 24upx;
			color: #232323;

			.protocol {
				color: #FFBC21;
				margin-top: 10upx;
				display: flex;
				justify-content: center;
			}
		}

	}

	.oauth {
		// @media all and (max-height: 1206upx) {
		// 	display: none;
		// }


		// position: absolute;
		// bottom: 50upx;
		// width: 100%;

		.text {
			width: 100%;
			height: 60upx;
			display: flex;
			justify-content: center;
			align-items: center;
			color: rgba($color: #E1E4E5, $alpha: 0.8);
			font-size: 28upx;
		}

		.list {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 20upx 0;

			.yticon {
				font-size: 80upx;
				margin: 0 30upx;
				color: #767777;
			}
		}
	}
</style>
